#!/bin/bash

#  Name:		dzen2_linuxrules
#  Version:		0.7
#  Depends:		dzen2, linuxrules
#  Purpose:		This script translates linuxrules
#               monitoring data into fancy colourized
#               dzen2 bar output for xmonad, ratpoison
#               and different light WMs It is part of
#               linuxrules extended examples.

#  Creation:	Sat Oct 09 2010 (Lost and rewritten)
#  Modified:	Sun Jan 16 2011, 00:44:13

#  <http://linuxrules.googlecode.com>
#  in case of bug issues, updates, proposals or comments
#
#  Copyright (C) 2010 Mario García H.
#
#  "THE BEER-WARE LICENSE" (Revision 42):
#  <code933k (AT) mail> wrote this file. As long as you
#  retain this notice you can do whatever you want with
#  this stuff. If we meet some day, and you think this
#  stuff is worth it, you can buy me a BEER in return,
#  Mario García H.
#
#  THIS IS FREE SOFTWARE PROVIDED AS-IS THERE IS NO
#  WARRANTY, TO THE EXTENT PERMITTED BY LAW.

# Background color for bar and masks
# (i.e., characters used to fill space)
BGC='#00071A'

# My total RAM memory is 4Gb. I trigger
# kernel-cache-flush so that wasted memory can be
# recovered when system hits less than 500 Mb This
# is also a TRIGGER COMMANDS ON EVENTS EXAMPLE

activate_cache_flush() {
    if ps -C kernel-cache-flush.sh >/dev/null \
    || ps -C kernel-cache-flush >/dev/null
    then
        return 1
    else
        kernel-cache-flush &
    fi
}

# Note: Most current sleep implementations work with
# non integer values too. i.e., SLEEP=0.5 could work on
# many systems. We test firstly the sleep program so
# that we don't get surprices later.
sleep 0.1 2>/dev/null \
&& SLEEP_BUG=false    \
|| SLEEP_BUG=true

SLEEP=1
TOTALTIME=0

# Symple way to display mails (with mailx) more
# instructions way below.
MAIL_CACHE=~/.local/cache/iN
ELN=$(head -1 $MAIL_CACHE/elite.wc)
GLN=$(head -1 $MAIL_CACHE/gmail.wc)
MLN=$(head -1 $MAIL_CACHE/mlibr.wc)

# Embed system data and keep looping indefinitely
while eval $(linuxrules)
do
    TOTALTIME=$(($TOTALTIME+$SLEEP))
    # Dynasleep™ LOL, helps avoiding extra charge over
    # the system whenever there is high load.
    # Specially nice for netbooks and gaming rigs.
    DYNASLEEP=$(echo "$SLEEP * $LOAD_LAST" | bc)
    if test $(echo "$DYNASLEEP < 1" | bc) -eq 1
    then
        DYNASLEEP=$SLEEP
    fi

    # Variable from where we will feed all data to
    # dzen2. Initialize on every loop entry.
    OUTPUT=''
	
	# MEDIA
    # Show media sub directories (actually, mounted
    # partitions)
    #
    # That long |sed line is just for "beautifying" OUTPUT
    # in my own dzen2 bar Check out asvm
    # <http://lifehacks.googlecode.com> if you want a
    # light and nice USB MMC/SD media automounter.

    if test -n "$MEDIA"
    then
        OUTPUT="$OUTPUT ^fg()media:$(echo $MEDIA \
        | sed '
        s/\s/\^fg('blue')\]\[\^fg(gray80)/g
        s/^/\^fg('blue')\[ \^fg(gray)/g;
        s/$/\^fg('blue') \]/g'
        )"
    fi

    # UPTIME
    OUTPUT="$OUTPUT  ^fg()up: ^fg($C_XX)$UPTIME2  ^fg()load: ^fg(blue)$LOAD_LAST"


    # CPU LOAD
    # We iplicitly test whether CPU values exist so
    # they will be counted dynamically if, for example,
    # a CPU was hotplugged.
    result=0
    format_cpuload() {
        # Colors
        if test $1 -gt 80
        then
            COLOR="^fg($C_NO)"
        elif test $1 -gt 50
        then
            COLOR="^fg($C_WC)"
        else
            COLOR="^fg($C_OK)"
        fi

        BAR=$(($1*13/100))
        test $BAR -eq 0 && BAR=1

        # Correct number of characters

        OUTPUT="${OUTPUT}${COLOR}^p(;+$((13-$BAR)))^r(7x$BAR)^p()^fg() "
    }
    
    OUTPUT="${OUTPUT}^fg()  cpu: "
    
    # CPU0 is probably always online. However, CPU#
    # could be hotplugged or shutdown at any moment.
    # Use tests for CPU0 + n:
    format_cpuload "$CPULOAD0"
    test -n "$CPULOAD1" && format_cpuload "$CPULOAD1"


    # CPU TEMPERATURE
    format_temp() {
     # Colors
        if test $1 -gt 72
        then
            COLOR="^fg($C_NO)"
        elif test $1 -gt 65
        then
            COLOR="^fg($C_WC)"
        else
            COLOR="^fg($C_OK)"
        fi

        OUTPUT="${OUTPUT} ${COLOR}${1}°C"
    }

    format_temp $TEMP1

    # LOWER POWER TO FORCE SYSTEM COOLING (ie. HOT CPU)
    if test -n "$TEMP1" -a $TEMP1 -gt 83
    then
        power2 s v low
        _MYALARM=true
    elif test -n "$_MYALARM"
    then
        if test -n "$_POWER_STATUS"
        then
            $_POWER_STATUS
        else
            test $ACAD = 'on-line' && power2 p v
        fi

        unset _MYALARM
    fi

    # FREE RAM MEMORY
    OUTPUT="$OUTPUT^fg()  free: "
    if test $MEMFREE    -gt 2000
    then
        COLOR=$C_OK
    elif test $MEMFREE  -gt 1000
    then
        COLOR=$C_XX
    elif test $MEMFREE -gt 400
    then
        COLOR=$C_WC
    else
        COLOR=$C_NO
        activate_cache_flush
    fi
    OUTPUT="${OUTPUT}^fg($COLOR)${MEMFREE}"

	# BATTERY(IES) CHARGE
    OUTPUT="$OUTPUT  ^fg()batt: "

    format_batt_charge() {
        # Charge bar colors
        if test $1 -gt 70
        then
            COLOR="^fg($C_XX)$1 "
        elif test $1 -gt 50
        then
            COLOR="^fg($C_OK)$1 "
        elif test $1 -gt 20
        then
            COLOR="^fg($C_WC)$1 "
        else
            COLOR="^bg($C_NO)^fg($C_LW)$1^bg() "
        fi

        BAR=$(($1*13/100))
        test $BAR -eq 0 && BAR=1

        OUTPUT="${OUTPUT}${COLOR}^p(;+$((13-$BAR)))"
        OUTPUT="$OUTPUT^r(7x$BAR)^p()^fg() "
    }

    format_batt_charge "$BATTCH1"

    # Shutdown cleanly when levels are unbearable
    test -z "$BATTREM1" \
    || OUTPUT="$OUTPUT ^fg(blue)[^fg(red)$BATTREM1^fg(blue)]"
    test $BATTCH1 -lt 2 && sudo dt-halt

	# WIRELESS LINK
    # We should test firstly whether there's link. If
    # not, output link down.
    format_wifi_link() {
        if test $1 -gt 60
        then
            COLOR="^fg($C_OK)"
        elif test $1 -gt 40
        then
            COLOR="^fg($C_WC)"
        else
            COLOR="^fg($C_NO)"
        fi
        
        OUTPUT="$OUTPUT ${COLOR}$1 ^fg()$WBEACON1"
    }
    
    if test -n "$WLINK1"
    then
        # WIRELESS ROUTER
        # "essid" dynamic info. Linuxrules can't
        # provide this right now.  I know this appears
        # to be complicated.  Just copy and paste,

        # changing $WIFACE1 for your own linuxrules
        # wifi interface...
        OUTPUT="$OUTPUT $(iwconfig $WIFACE1 2>/dev/null\
        | awk 'NR < 2 {gsub(/ESSID:\"|\"/, ""); \
        print " ^ca(1,show_wifi_status.sh)^fg()wifi: ^fg('$C_XX')" $4 "^ca()"}')"

        format_wifi_link $WLINK1
    else
        OUTPUT="$OUTPUT  ^ca(1,show_wifi_status.sh)^fg()wifi: ^fg($C_NO)nolink^ca() "
    fi


	# EXTRA TEMPERATURES
    OUTPUT="$OUTPUT "
    format_temp $TEMP2
    format_temp $TEMP3
    format_temp $TEMP4

#################################################
## TRIGGER POWER2 WHENEVER SWITCH IS UNPLUGGED ##
#################################################

# This calls an independent suspend_routine whatever it
# is: s2ram, s2disk, echo mem >, etc.
case $LID in
    closed )
        if $NOT_ISSUED
        then
            SUSPEND="$(which s2ram)"
            sudo $SUSPEND -f 2>/dev/null
            NOT_ISSUED=false
        fi
    ;;
    open )
        NOT_ISSUED=true
    ;;
esac


# Introducing ACAD_ISSUED avoids triggering power2
# every time linuxrules values are read. Any power
# saver routine must be triggered just once. Else,
# it is a power wasting routine..!
case $ACAD in
    on-line )
        if $ACAD_ISSUED
        then
            power2 p b 3 v 2>/dev/null
            ACAD_ISSUED=false
        fi
    ;;
    off-line )
        if ! $ACAD_ISSUED
        then
            power2 s b 1 v 2>/dev/null
            ACAD_ISSUED=true
        fi
    ;;
esac

# MAIL COUNT
# Linuxrules does not report email itself. That is
# beyond scope.  However, we can check it out easily
# (say every 5 minutes) with a remind at or cron job:
# mail -A myaccount -H > myaccount_headers then a grep
# "^ U" myaccount_headers | wc -l > newmail will finish
# the job of counting how many new mails we have.
#
# Notice we also cached headers so that they can be
# checked out externally with any menu program like
# dzen2, zenity, kdialog.  And DYNASLEEP keeps working
# even here.
# 
# This is a simple and effective procedure
# through *nix mailX program. Note: Full set of system
# bloats not required :)

if test $(echo $TOTALTIME % 150 | bc) -eq 0
then
    ELN=$(head -1 $MAIL_CACHE/elite.wc)
    GLN=$(head -1 $MAIL_CACHE/gmail.wc)
    MLN=$(head -1 $MAIL_CACHE/mlibr.wc)
fi

OUTPUT="$OUTPUT  ^fg()br: ^fg(blue)$SCREENBR0^fg() \
^ca(1,show_mail_headers.sh) mail:^fg(blue) e$ELN g$GLN m$MLN^ca() "

# WEATHER
if test -n "$NOAA_TEMP_C"
then
    OUTPUT="$OUTPUT ^ca(1,show_full_weather_log.sh)"
    OUTPUT="$OUTPUT^fg()$NOAA_CITY ^fg($C_XX)"
    OUTPUT="$OUTPUT$NOAA_TEMP_C°C ^fg()$NOAA_SKY2 ^ca()"
else
    OUTPUT="$OUTPUT ^fg()No weather"
fi

# CLEANUP
unset BATTREM1 CPULOAD1 MEDIA

# Send output to dzen2:
printf "$OUTPUT\n"

# Wait before starting once again but check wether
# sleep handles float point for dynasleep to work.
$SLEEP_BUG \
&& sleep $SLEEP \
|| sleep $DYNASLEEP
# done
done | dzen2 -x 428 -xs 1 \
-ta c -fg "$C_LW" -bg "$BGC" \
-fn "Bebas Neue:regular:pixelsize=17"

# vim:tw=55:
